#include "log.h"

#include <FS.h>
#include <LittleFS.h>
#include <WiFiUdp.h>
#include <NTPClient.h>

// WiFiUDP g_udp_ntp;
char date_time[64]; // 获取时间戳

String g_folder_log = "/log";
String g_log_file_pre = "log-000001.log";


// put function declarations here:
String get_current_time()
{
  configTime(8 * 3600, 0, "ntp.aliyun.com", "time.nist.gov", "0.pool.ntp.org");
  struct tm time_mseconds;
  time_mseconds.tm_year = 0;
  getLocalTime(&time_mseconds, 5000);
  sprintf(date_time, "%04d-%02d-%02d %02d:%02d:%02d", (time_mseconds.tm_year) + 1900, (time_mseconds.tm_mon) + 1, time_mseconds.tm_mday, 
                                                      time_mseconds.tm_hour, time_mseconds.tm_min, time_mseconds.tm_sec);
  return String();
}
void LOG(LOG_TYPE log_type, char* log_info)
{
  // g_time_client.update();
  // unsigned long time_stamp = g_time_client.getEpochTime();
  // struct tm *days = gmtime((time_t*)&time_stamp);
  // Serial.printf("\nNow is : \n", (time_mseconds.tm_year) + 1900, (time_mseconds.tm_mon) + 1, time_mseconds.tm_mday, time_mseconds.tm_hour, time_mseconds.tm_min, time_mseconds.tm_sec);
  Serial.println(date_time);
  char log_content[128] = {0};
  switch (log_type){
    case LOG_INFO:
        sprintf(log_content, "%s    INFO: %s", date_time, log_info);
        break;
    case LOG_ERR:
        sprintf(log_content, "%s   ERROR: %s", date_time, log_info);
        break;
    case LOG_ALRM:
        sprintf(log_content, "%s   ALARM: %s", date_time, log_info);
        break;
    case LOG_WARN:
        sprintf(log_content, "%s WARNING: %s", date_time, log_info);
        break;
    default:
        break;
  }
  
//   Serial.println(log_content);

  if (LittleFS.begin())
  {
    File log_file;
    if (LittleFS.exists(g_log_file_pre)){
        log_file = LittleFS.open(g_log_file_pre, "a");
    }
    else{
        LittleFS.format();
        log_file = LittleFS.open(g_log_file_pre, "w");
        Serial.println("Log open with write....");
    }
    log_file.println(log_content);
    Serial.printf("The log file size is %d Byte\n", log_file.size());
    log_file.close();
  }
  else {
    Serial.println("SPIFFS begin failed");
  }

  // Serial.println("*********************Output log begin*********************");
  // File log_file = SPIFFS.open(g_log_file_pre, "r");
  // Serial.println(log_file.readString().c_str());
  // log_file.close();
  // Serial.println("**********************Output log end**********************");

  Serial.println("Log end...");
  LittleFS.end();
}
